/**
 * @Author: jbt
 * @Date:   2017-03-14T18:17:44+08:00
 * @Email:  947809647@qq.com
 * @Last modified by:   jbt
 * @Last modified time: 2017-03-22T10:10:52+08:00
 */
import { sendSms, login, updateState, showMsg } from '../../vuex/action'
import jsCookie from 'js-cookie'
import session from '../../util/session'

export default {
  name: 'Login',
  data() {
    return {
      email: '',
      password: '',
      smscode: ''
    }
  },
  vuex: {
    getters: {
      sendSmsDisabled: state => state.sendSmsDisabled
    },
    actions: {
      xSendSms: sendSms,
      xLogin: login,
      xShowMsg: showMsg,
      xUpdateState: updateState
    }
  },
  methods: {
    sendSms() {
      if (!this.email.length) {
        return this.xShowMsg({
          type: 'danger',
          content: '请输入用户名'
        })
      }
      this.xSendSms({
        email: this.email
      })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    },
    submit() {
      var content = ''
      if (!this.email.length) {
        content = '请输入用户名'
      } else if (!this.password.length) {
        content = '请输入密码'
      } else if (env === 'prod' && !this.smscode.length) {
        content = '请输入手机验证码'
      }
      if (content.length) {
        this.xShowMsg({
          type: 'danger',
          content: content
        })
      } else {
        this.xLogin({
          email: this.email,
          password: this.password,
          verifySms: this.smscode
        })
          .then(() => {
            // set cookie
            jsCookie.set(SESSION_COOKIE_NAME, '1')
            session.set('user_name', this.email)
            if (document.referrer !== document.URL && document.referrer.indexOf('manage.igoldenbeta.com') > -1) {
              location.href = document.referrer
            } else {
              location.href = client.htmlPath + '/index.html'
            }
          })
          .catch((res) => {
            this.xShowMsg({
              type: 'danger',
              content: res.error_msg
            })
          })
      }
    }
  },
  watch: {
    sendSmsDisabled() {
      var btn = this.$els.btnSendSms
      if (this.sendSmsDisabled) {
        btn.setAttribute('disabled', 'disabled')
        let n = 5
        let ticker = setInterval(() => {
          btn.innerText = n + 's后重试'
          n--
          if (n < 0) {
            clearInterval(ticker)
            this.xUpdateState('SEND_SMS_DISABLED', false)
          }
        }, 1000)

        this.xShowMsg({
          type: 'success',
          content: '验证码发送成功'
        })
      } else {
        btn.removeAttribute('disabled')
        btn.innerText = '发送验证码'
      }
    }
  }
}
